#encoding:UTF-8
#######################################################################
# Copyright (C)                                                       #
# 2016 - 2018 Shangtong Zhang(zhangshangtong.cpp@gmail.com)           #
# 2016 Jan Hakenberg(jan.hakenberg@gmail.com)                         #
# 2016 Tian Jun(tianjun.cpp@gmail.com)                                #
# 2016 Kenta Shimada(hyperkentakun@gmail.com)                         #
# Permission given to modify the code as long as you keep this        #
# declaration at the top                                              #
#######################################################################

from enviroment.env import State
from enviroment.states import all_states

class Judger:
    # @player1: the player who will move first, its chessman will be 1
    # @player2: another player with a chessman -1
    # @feedback: if True, both players will receive rewards when game is end
    def __init__(self, player1, player2):
        self.p1 = player1
        self.p2 = player2
        self.current_player = None
        # self.p1_symbol = 1
        # self.p2_symbol = -1
        # 为p1 p2用户初始化状态值函数V
        # self.p1.set_symbol(self.p1_symbol)
        # self.p2.set_symbol(self.p2_symbol)
        

    def reset(self):
        # p1 p2的遍历对象清空
        self.p1.reset_history()
        self.p2.reset_history()

    def alternate(self):
        while True:
            yield self.p1
            yield self.p2

    # @print: if True, print each board during the game
    def play(self, print=False):
        alternator = self.alternate()
        current_state = State()  # 初始化棋盘状态对象
        self.reset()             #player1,2的历史记录清空
        
        self.p1.add_state(current_state)
        self.p2.add_state(current_state)
        
        while True:
            player = next(alternator)
            
            if print:
                current_state.print()
                
            [i, j, symbol] = player.act()
            
            next_state_hash = current_state.next_state(i, j, symbol).hash()
            current_state, is_end = all_states[next_state_hash]
            
            self.p1.add_state(current_state)
            self.p2.add_state(current_state)
            
            if is_end:
                if print:
                    current_state.print()
                return current_state.winner

